﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Principal;

namespace PreContractWeb
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
//#if DEBUG
//                this.txtname.Text = "jun f wu";
//                this.txtpwd.Text = "a";
//#endif
                //this.btnlogin.Attributes.Add("onclick", "event.returnValue=false;if(CheckBadWords()) {event.returnValue=true;} else {event.returnValue=false;}");

                FormsAuthentication.SignOut();
            }
        }

        private void FormAuthentication(string username)
        {

            //create form authentication ticket.
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                2,         // Ticket version
                username,  // Username associated with ticket
                //true,    //isPersistent
                DateTime.Now,// Date/time issued
                DateTime.Now.AddHours(1),//time to expire
                true,       // "true" for a persistent user cookie
                "",          // User-data, in this case the roles
                FormsAuthentication.FormsCookiePath);// Path cookie valid for

            // Encrypt the cookie using the machine key for secure transport
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));

            // Set the cookie's expiration time to the tickets expiration time
            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;


            // Add the cookie to the list for outgoing response
            Response.Cookies.Add(cookie);

            // Create an Identity.
            GenericIdentity id = new GenericIdentity(ticket.Name, "PreContractWebAuthentication");

            // This principal flows throughout the request.
            GenericPrincipal principal = new GenericPrincipal(id, (string[])null);

            //string name = principal.Identity.Name;

            BEGDC.PreContract.BLL.Authentication.PCPrincipal princi = BEGDC.PreContract.BLL.Authentication.PCPrincipal.GetPrincipal(principal);

            princi.Reload();

            BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.Login, "Login", username);

            if (Request.Cookies["RedirectURL"] != null)
            {
                if (Request.Cookies["RedirectURL"].Value != null)

                    Page.Response.Redirect(HttpContext.Current.Request.Cookies["RedirectURL"].Value.ToString());
            }
            string url = System.Web.Security.FormsAuthentication.GetRedirectUrl(username, false);

            if (url == string.Empty)
            {
                Response.Redirect("~/Default.aspx");
            }
            else
            {

                Response.Redirect(System.Web.Security.FormsAuthentication.GetRedirectUrl(username, false));
            }

        }


        protected void btnlogin_Click(object sender, ImageClickEventArgs e)
        {
            string outMessage = string.Empty;
            string username = BaseFunction.SafeSQL(this.txtname.Text.Trim());
            string password = this.txtpwd.Text.Trim();

            if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsUseLDAP"]))
            {
                //int islogin = -1;
                bool islogin = false;
                try
                {

                    //string adPath = System.Configuration.ConfigurationManager.AppSettings["LDAP_Path"];
                    //string domain = System.Configuration.ConfigurationManager.AppSettings["LDAP_Domain"];
                    //string adType = System.Configuration.ConfigurationManager.AppSettings["LDAP_AuthenticationType"];

                    //BEGDC.Utility.LdapAuth.LdapAuthentication adAuth = new BEGDC.Utility.LdapAuth.LdapAuthentication(adPath, adType);
                    //islogin = adAuth.IsAuthenticated(domain, username, password);
                    islogin = true;
                }
                catch
                {
                    this.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + AlertMessage.UserNameOrPwdError + "')</script>");
                    return;
                }

                if (islogin)  //success
                {
                    BEGDC.PreContract.BLL.IEmployee employeeservice = (BEGDC.PreContract.BLL.IEmployee)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Employee_Service];

                    BEGDC.PreContract.DAL.Employee employee = employeeservice.GetEmployeeByCILAccount(username);


                    if (employee == null)
                    {
                        this.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + AlertMessage.UserNotExist + "')</script>");
                        return;
                    }
                    else if (!employee.Active)
                    {

                        this.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + AlertMessage.AccountNotActive + "')</script>");
                        return;

                    }
                    else
                    {
                        FormAuthentication(username);
                    }

                }


                else
                {

                    this.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + AlertMessage.UserNameOrPwdError + "')</script>");
                    return;

                }

            }
            else
            {

                BEGDC.PreContract.BLL.IEmployee employeeservice = (BEGDC.PreContract.BLL.IEmployee)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Employee_Service];

                BEGDC.PreContract.DAL.Employee employee = employeeservice.GetEmployeeByCILAccount(username);


                if (employee == null)
                {
                    this.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + AlertMessage.UserNotExist + "')</script>");
                    return;
                }
                else if (!employee.Active)
                {

                    this.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + AlertMessage.AccountNotActive + "')</script>");
                    return;

                }
                else
                {
                    FormAuthentication(username);
                }

            }
        }
    }
}
